package com.itheima.ai.controller;

import cn.hutool.core.collection.CollUtil;
import com.itheima.ai.service.IChatHistoryService;
import com.itheima.ai.vo.MessageVO;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对话历史控制器
 *
 * @Author mr.wu
 * @Date 2025-11-4 15:24
 */
@CrossOrigin
@RestController
@RequestMapping("/ai/history")
public class ChatHistoryController {

    @Autowired
    private IChatHistoryService chatHistoryService;

    /**
     * 查询会话列表接口，列表中的元素是会话ID
     * @param type  业务类型：chat、service、pdf
     * @return
     */
    @GetMapping("/{type}")
    public List<String> getChatIdList(@PathVariable String type){
        return chatHistoryService.findConversationIds(type, null);
    }


    @Autowired
    private ChatMemory chatMemory;

    /**
     * 查询会话具体历史：查询某个会话中多轮对话的消息列表
     * @param type
     * @param chatId
     * @return
     */
    @GetMapping("/{type}/{chatId}")
    public List<MessageVO> getMessageList(@PathVariable String type,@PathVariable String chatId) {
        //1. 获取会话记忆里某会话ID对应的消息列表
        List<Message> messageList = chatMemory.get(chatId);
        if(CollUtil.isEmpty(messageList)) {
            return Collections.emptyList();
        }

        //2. 类型转换
        List<MessageVO> messageVOList = messageList.stream().map(MessageVO::new).collect(Collectors.toList());
        return messageVOList;
    }
}
